# 主要是需要moviepy这个库
import getpass
import json
import subprocess
from datetime import datetime, timedelta

import cv2
from moviepy.editor import *
import os
import glob2 as gb

from DBAction import DBAction


def combine_video():
    """合并视频"""
    # TODO moviepy太慢，替换为FFmpeg
    video_path_list = gb.glob(os.path.join(r'D:\pocket48image\fanpai', '**/*.mp4'))
    video_list = []
    count = 0
    for path in video_path_list:
        # vc = cv2.VideoCapture(path)
        # print(vc.get(cv2.CAP_PROP_FRAME_WIDTH), vc.get(cv2.CAP_PROP_FRAME_HEIGHT))

        # 载入视频,target_resolution第一个是高度，第二个宽度。一个为None会按比例缩放
        video = VideoFileClip(path, target_resolution=[1000, None])
        # 添加到数组
        print(video.size)
        video_list.append(video)
        count+=1
        if count == 4:
            break

    # 拼接视频
    final_clip = concatenate_videoclips(video_list, method='compose')
    # 生成目标视频文件
    final_clip.write_videofile("./target.mp4", fps=24, threads=2)


def text_file(video):
    # 添加字幕文件到视频
    os.chdir('./')  # 定位相对路径

    cmd = f'ffmpeg -i "{video}" -lavfi "subtitles=subtitle.srt:force_style=\'Alignment=2,OutlineColour=&H100000000,' \
          f'BorderStyle=3,Outline=1,Shadow=0,Fontsize= 10,MarginV=3\'" -vcodec h264_nvenc  "sub_video.mp4"  -y'
    subprocess.call(cmd, shell=True)


def get_zimu():
    """生成字幕文件"""
    db = DBAction('pocket48')
    result = db.data_inquiry_all("SELECT m.name,r.msg_type,r.ext_info,r.msg_time "
                                 "FROM pocket48.roommsg r left join "
                                 "member m on m.memberid=r.memberid where r.msg_type in (11) "
                                 "and m.fan_num<600000 and m.fan_num>0 "
                                 "and r.msg_time>'2021-04-06 00:00:00' and r.msg_time<'2021-06-13 08:00:00'")
    file_question_map = {}
    for data in result:
        ext = json.loads(data[2])
        question = ext['question']
        filename = data[3].strftime("%Y-%m-%d_%H-%M-%S") + '.mp4'
        file_question_map[filename] = question

    def getTotalTime(file_path):
        """获取视频长度，返回秒"""
        total = 0
        cap = cv2.VideoCapture(file_path)
        if cap.isOpened():
            rate = cap.get(5)  # 获取帧率
            fraNum = cap.get(7)  # 获取帧数
            duration = fraNum / rate
            total += duration
        return total

    # 写字幕文件
    destScript = open('./subtitle.srt', 'wt', encoding='utf-8')
    seqNo = 1
    startTime = datetime(1980, 1, 1, 0, 0, 0)
    video_path_list = gb.glob(os.path.join(r'D:\pocket48image\fanpai', '**/*.mp4'))
    for path in video_path_list:
        file = path.split('\\').pop()
        ques = file_question_map[file]

        endTime = startTime + timedelta(milliseconds=getTotalTime(path)*1000)
        destScript.write(str(seqNo) + '\n')  # 写字幕序号
        destScript.write(startTime.strftime("%X") + ',0 --> ' + endTime.strftime("%X") + ',0\n')
        destScript.write(ques + '\n')
        destScript.write('\n')
        seqNo += 1
        startTime = endTime
    destScript.close()


if __name__ == '__main__':
    combine_video()
    get_zimu()
    text_file('target.mp4')
